<template>
  <a-button-group>
    <template
      v-for="item in btnGroup"
      :key="item.operator"
    >
      <a-button
        v-if="props.type === 'btn'"
        :size="props.btnSize"
        :loading="loading"
        @click="$emit('recordOperator',item.operator, props.record, setLoading)"
      >
        {{ item.name }}
      </a-button>

      <a-link
        v-if="props.type === 'link'"
        :loading="loading"
        @click="$emit('recordOperator', item.operator, props.record, setLoading)"
      >
        {{ item.name }}
      </a-link>
    </template>
    <a-dropdown v-if="hasMore" position="tr">
      <a-button
        v-if="props.type === 'btn'"
        :size="props.btnSize"
        :loading="loading"
      >
        <template #icon>
          <icon-more />
        </template>
      </a-button>
      <a-link v-if="props.type === 'link'" :loading="loading">
        <template #icon>
          <icon-more />
        </template>
      </a-link>
      <template #content>
        <a-doption
          v-for="item in moreGroup"
          :key="item.operator"
          @click="$emit('recordOperator', item.operator, props.record, setLoading)"
        >
          {{ item.name }}
        </a-doption>
      </template>
    </a-dropdown>
  </a-button-group>
</template>

<script lang="ts" setup>
import { defineProps, defineEmits, ref, watch, PropType } from 'vue';
import { hasPermission } from '@/utils/permission';
import { slice } from 'lodash';
import useLoading from '@/hooks/loading';
import { ColumnOperator } from '@/components/table/column-operator/type';

const emits = defineEmits(['recordOperator']);

const props = defineProps({
  type: {
    type: String,
    default: () => {
      return 'link';
    }
  },
  btnSize: {
    type: String,
    default: () => {
      return 'middle';
    }
  },
  btnNumber: {
    type: Number,
    default: () => {
      return 3;
    }
  },
  config: {
    type: Array,
    default: () => {
      return [];
    }
  },
  record: {
    type: Object,
    default: () => {
      return null;
    }
  }
});

const { loading, setLoading } = useLoading(false);

const hasMore = ref<boolean>(false);

const btnGroup = ref<any>([]);

const moreGroup = ref<any>([]);

watch(
  () => props.config,
  (value) => {
    //  过滤权限
    const btn = props.config?.filter(item => {
      return hasPermission(item.permission);
    });
    hasMore.value = btn.length > props.btnNumber;
    if (hasMore.value) {
      btnGroup.value = slice(btn, 0, 2);
      moreGroup.value = slice(btn, 2, btn.length);
    } else {
      btnGroup.value = btn;
      moreGroup.value = [];
    }
  },
  { deep: true, immediate: true }
);
</script>

<style scoped lang="less">

</style>